package com.flappySeeker.controller;



import java.io.IOException;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.mail.Session;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import javax.servlet.http.HttpServletResponse;


import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.flappySeeker.common.BaseDaoImp;
import com.flappySeeker.model.TbUserinfo;
import com.flappySeeker.util.GetTools;
import com.flappySeeker.util.SmartyManager;
import com.flappySeeker.util.alipay.config.AlipayConfig;
import com.flappySeeker.util.alipay.util.AlipaySubmit;

@Controller
@RequestMapping("/contoller")
public class ReviewAction {
	
	@Autowired
	private BaseDaoImp baseDaoImp;
	
	public BaseDaoImp getBaseDaoImp() {
		return baseDaoImp;
	}
	public void setBaseDaoImp(BaseDaoImp baseDaoImp) {
		this.baseDaoImp = baseDaoImp;
	}
	/**
	 * 插入用户
	 * 匹配数据
	 * @param user
	 * @param request
	 * @param mbti 3个 ISTJ,ISFJ,INFJ,INTJ,ISTP, ISFP,INFP, INTP,ESTP, ESFP, ENFP,ENTP, ESTJ, ESFJ, ENFJ,ENTJ
	 * @param holland 3个  S,E,C,R,I,A
	 * @return /contoller/save.do  htm
	 * method=RequestMethod.POST
	 */
	@RequestMapping(value="/save")
	@ResponseBody
	public String  Info(HttpServletRequest request,HttpSession session) {
		try {
			Object cmdurl2sf = session.getAttribute("cmdurl2sf");
			Map<String, Object> resmap = new HashMap<String, Object>();
			boolean ispay =(cmdurl2sf!=null&&cmdurl2sf.toString().equals("sf"))?true:false;
			String fname = GetTools.dateTstr(new Date(), "yyyyMMddHHmmss")
					+GetTools.randomInt(6)+Constants.xstory_type;//生成文件名字yyyyMMddHHmmss+num6.htm
			File f=new File(Constants.getXSTORY_PATH()+fname );

			/****************************************** 开始mbti*****************************************/
			String mbtians =request.getParameter(MBTI.TEST_SUFF);
			System.out.println(mbtians+"   +++++++++++++++++++++++++");
			Map<String, Integer> msmap=new HashMap<String, Integer>();
			Object userid = request.getSession().getAttribute("sf_userid");
			Object username = request.getSession().getAttribute("sf_username");
			if(StringUtils.isEmpty(mbtians)){//没有提交mbti答案，去数据库查询，一般是做了阶段一的做收费测试
				if(userid!=null&&!StringUtils.isEmpty(userid.toString())){
					Object mbtianstr = baseDaoImp.sqlforobj(Sql.MBTI_ANSWER,userid);
					if(!mbtianstr.equals("0")){
						msmap=(Map<String, Integer>) JSON.parse( mbtianstr.toString());
					}
				}
			}else{
				msmap= GetTools.strTmap(mbtians);
			}
			if(msmap.size()==0){
				return "没有传MBTI答案，也找不到MBTI对应的答案记录";
			}
			if(ispay&&request.getParameter(HOLLAND.TOTAL_E)==null){//无阶段二答案保存，返回next
				//将答案放数据库
				if(userid!=null&&!StringUtils.isEmpty(userid.toString())){
					baseDaoImp.update(Sql.UPMBTI_ANSWER, JSON.toJSONString(msmap),userid);
				}
				return "next";
			}
			
			/*if(!ispay){//不收费已经测试过的，并且地址存在直接返回地址
				Object resulturl = baseDaoImp.sqlforobj(Sql.MBTI_RESULTSURL,userid);
				if(resulturl!=null){
					File tempff = new File(Constants.getBasepath()+resulturl);
					if(tempff.exists()){
						return resulturl.toString();
					}
				}
			}*/
			
			//模拟数据
			resmap.put("ispay", ispay?1:0);
			resmap.put("username", username);
			
			StringBuilder sumbti=new StringBuilder()//同分处理以后者
			.append( GetTools.mapval(msmap, MBTI.E)>GetTools.mapval(msmap, MBTI.I)?MBTI.E:MBTI.I)
			.append( GetTools.mapval(msmap, MBTI.S)>GetTools.mapval(msmap, MBTI.N)?MBTI.S:MBTI.N)
			.append(GetTools.mapval(msmap, MBTI.T)>GetTools.mapval(msmap, MBTI.F)?MBTI.T:MBTI.F)
			.append(GetTools.mapval(msmap, MBTI.J)>GetTools.mapval(msmap, MBTI.P)?MBTI.J:MBTI.P);
			
			
			resmap.put("mbtien", sumbti.toString());//ISTJ
			resmap.put("mbtimap", msmap);
			System.out.println(msmap);
			resmap.put("mbtizh", MBTI.getMbtiMap().get(sumbti.toString()));//中文类型
			resmap.put("mbticontent", MBTI.getMbtiConten().get(sumbti.toString()));//mbti描述
			
			/****************************************** 结束mbti*****************************************/
			
			
			/****************************************** 开始HOLLAND*****************************************/
			if(ispay){
				Map<String, Integer> hsmap=new HashMap<String, Integer>();
				hsmap.put(HOLLAND.E,Integer.parseInt(request.getParameter(HOLLAND.TOTAL_E).toString()));//20
				hsmap.put(HOLLAND.I,Integer.parseInt(request.getParameter(HOLLAND.TOTAL_I).toString()));//20
				hsmap.put(HOLLAND.S,Integer.parseInt(request.getParameter(HOLLAND.TOTAL_S).toString()));//20
				hsmap.put(HOLLAND.R,Integer.parseInt(request.getParameter(HOLLAND.TOTAL_I).toString()));//20
				hsmap.put(HOLLAND.A,Integer.parseInt(request.getParameter(HOLLAND.TOTAL_A).toString()));//20
				hsmap.put(HOLLAND.C,Integer.parseInt(request.getParameter(HOLLAND.TOTAL_S).toString()));//20
				
				ArrayList<Entry<String, Integer>> hentry=GetTools.sortByValue(hsmap);
				StringBuilder hres=new StringBuilder();
				List<String> hollandcontent=new ArrayList<String>(); 
				StringBuilder hollandzh =new StringBuilder();
				for (int i=0;i<3;i++) {
					String k=hentry.get(i).getKey();
					hres.append(k);
					hollandzh.append("、"+HOLLAND.getHollandMap().get(k)+"("+k+")");
					hollandcontent.add(HOLLAND.getHollandConten().get(k));
				}
//				List<Map<String, Object>> hollandary = getpro(hres.toString(),ispay,Sql.HOLLAND);//对应holland 各种类型专业下学校数据 
//				resmap.put("pros", hollandary);
				resmap.put("hollandmap", hsmap);
				resmap.put("hollandcontent", hollandcontent);
				resmap.put("hollandzh", hollandzh.substring(1));
				/****************************************** 开始 合并结果*****************************************/
				int num = ispay?Sql.PRO_MAX:Sql.PRO_MIN;
				String mtempstr = sumbti.toString();
				String htempstr =hres.toString();
				int count = baseDaoImp.sqlforint(Sql.PROFESSIONAL_COMPREHENSIVE_COUNT,mtempstr,htempstr);
				if(count<num){
					htempstr=StringUtils.substring(htempstr,0, htempstr.length()-1);
					System.out.println("专业太少情况做截取holland   "+htempstr);
				}	
				count = baseDaoImp.sqlforint(Sql.PROFESSIONAL_COMPREHENSIVE_COUNT,mtempstr,htempstr+"%");
				if(count<num){
					mtempstr=StringUtils.substring(mtempstr,0, mtempstr.length()-1);
					System.out.println("专业太少情况做截取MBTI  "+mtempstr);
				}	
				List<Map<String, Object>> mergelist = baseDaoImp.sqllistmap(//合并的结果集
							Sql.PROFESSIONAL_COMPREHENSIVE,mtempstr+"%",htempstr+"%", num);
					for (Map<String, Object> map : mergelist) {
						String zy=map.get("professionalid").toString();
						List<Map<String, Object>> unlist = baseDaoImp.sqllistmap(Sql.UNIVERSITY_BYPRO, 
								zy,ispay?Sql.UN_MAX:Sql.UN_MIN);
						map.put(Sql.UNVERSITY, unlist);
					}
					resmap.put("pros", mergelist);
				/****************************************** 结束  合并结果*****************************************/
				//已经支付的测试跳转页面
					/*try {
						FileUtils.writeStringToFile( f,SmartyManager.getInstance().templateout(resmap).toString(),"UTF-8");
					} catch (IOException e) {
						e.printStackTrace();
					}*/
			}
			/****************************************** 结束HOLLAND*****************************************/
			else{
				//将答案放数据库
				if(userid!=null&&!StringUtils.isEmpty(userid.toString())){
					baseDaoImp.update(Sql.UPMBTI_ANSWER, JSON.toJSONString(msmap),userid);
				}
				List<Map<String, Object>> mbtiary = getpro(sumbti.toString(),ispay,Sql.MBTI);//对应mbti 各种类型专业下学校数据  mbti=ESTL,mbtiary对应0=E,1=S,2=T,3=L
				resmap.put("pros", mbtiary);
			}
			try {
				FileUtils.writeStringToFile( f,SmartyManager.getInstance().templateout(resmap).toString(Constants.ENCODING_UTF8),Constants.ENCODING_UTF8);
				if(ispay){//清空序列号
					baseDaoImp.update(Sql.UP_VERIFICODE, userid);
				}
			} catch (IOException e) {
				e.printStackTrace();
				return  "生成报告错误" ;
			}
			String nfilepath=Constants.RESPATH+fname;
			//将地址放数据库
			if(userid!=null&&!StringUtils.isEmpty(userid.toString())){
				baseDaoImp.update(Sql.UP_RESULTSURL, nfilepath,userid);
			}
			return nfilepath;
		} catch (Exception e) {
			e.printStackTrace();
			return  "false" ;
		}
	}
	
	/**
	 * 根据holland或者mbti 获得对应专业学校
	 * @param hentry
	 * @return
	 */
	private List<Map<String, Object>> getpro(String strs, boolean ispay,String type) {
		try {
				int num = ispay?Sql.PRO_MAX:Sql.PRO_MIN;
				String tempstrs=strs;
				String sql =type.equals(Sql.HOLLAND)?Sql.PROFESSIONAL_HOLLAND_COUNT:Sql.PROFESSIONAL_MBTI_COUNT;
				int count = baseDaoImp.sqlforint(sql,tempstrs);
				if(count<num){
					tempstrs=StringUtils.substring(tempstrs,0, tempstrs.length()-1);
					System.out.println("太少情况做截取"+tempstrs);
				}
				count = baseDaoImp.sqlforint(sql,"%"+tempstrs+"%");
				if(count<num){
					tempstrs=StringUtils.substring(strs,0, 1)+StringUtils.substring(strs,2);
					System.out.println("太少情况做截取"+tempstrs);
				}
				
				List<Map<String, Object>> list = baseDaoImp.sqllistmap(
						type.equals(Sql.HOLLAND)?Sql.PROFESSIONAL_HOLLAND:Sql.PROFESSIONAL_MBTI, 
								"%"+tempstrs+"%",num);
				for (Map<String, Object> map : list) {
					String zy=map.get("professionalid").toString();
					List<Map<String, Object>> unlist = baseDaoImp.sqllistmap(Sql.UNIVERSITY_BYPRO, 
							zy,ispay?Sql.UN_MAX:Sql.UN_MIN);
					map.put(Sql.UNVERSITY, unlist);
				}
			return list;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 支付宝提交支付
	 * @param ordernum, subject,body,totalfee
	 * @throws SQLException 
	 * @throws IOException 
	 * @throws ServletException 
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value="/alipayto")
	private void alipayTo(TbUserinfo user,HttpServletRequest request,HttpServletResponse response) throws SQLException, IOException, ServletException{
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		String suc = "0", msg = "";
		String ordernum = GetTools.GetGUID();
		String totalfee = AlipayConfig.totalfee;
		int rnum1 = GetTools.randomInt(3);
		int rnum2 = GetTools.randomInt(4);
		int rnum3 = GetTools.randomInt(3);
		Map<String,Object> list = baseDaoImp.sqlformap("select userid,username,usertel,verificode,vsmscode,resultsurl from tb_userinfo where " +
				"username = '"+user.getUsername()+"' and " +
				"usertel = '"+user.getUsertel()+"'");
		if(list!=null){
			if(!list.get("vsmscode").equals(user.getVsmscode())){
				msg = "手机验证码不正确,请检查确认后重新输入或重新发送验证码。";
				out.print("[{'suc':'"+suc+"','msg':'"+msg+"'}]");
				return;
			} else {
				int r = baseDaoImp.update(
					"UPDATE tb_userinfo SET  ordernum = '"+ordernum+"',ispay ='1',verificode = '"+rnum1+""+rnum2+""+rnum3+"'  WHERE username = '"+user.getUsername()+"' and usertel = '"+user.getUsertel()+"' and userid = '"+list.get("userid")+"'"
				);
				if(r>0){
					Map<String, String> sParaTemp = new HashMap<String, String>();
			        sParaTemp.put("payment_type", "1");
			        sParaTemp.put("out_trade_no",ordernum);
			        sParaTemp.put("subject", AlipayConfig.SUBJECT);
			        sParaTemp.put("body", AlipayConfig.BODY);
			        sParaTemp.put("total_fee",totalfee+"");
			        sParaTemp.put("show_url", "");
			        sParaTemp.put("paymethod", "");
			        sParaTemp.put("defaultbank", "");
			        sParaTemp.put("anti_phishing_key", "");
			        sParaTemp.put("exter_invoke_ip", "");
			        sParaTemp.put("extra_common_param", "");
			        sParaTemp.put("r_pay", ""+rnum1+"");
			        sParaTemp.put("pay_m", ""+rnum2+"");
			        sParaTemp.put("last_p", ""+rnum3+"");
			        
			        //分润参数
//			      sParaTemp.put("subject", subject);
//					sParaTemp.put("body", body);
			        //分润收款账号1^提成金额1^说明1|
					sParaTemp.put("royalty_type", "10");
					sParaTemp.put("royalty_parameters", AlipayConfig.OUR_EMAIL+"^"+totalfee+"^"+ordernum+"分润转账");
					
			      //增加基本配置
			        sParaTemp.put("service", "create_direct_pay_by_user");
			        sParaTemp.put("partner",AlipayConfig.partner );
			        sParaTemp.put("return_url",AlipayConfig.RETURN_URL);
			        sParaTemp.put("notify_url", AlipayConfig.NOTIFY_URL);
			        sParaTemp.put("seller_email", AlipayConfig.SELLER_EMAIL);
			        sParaTemp.put("_input_charset", AlipayConfig.input_charset);

			        String strButtonName = "确认";

			        String sHtmlText = AlipaySubmit.buildRequest(sParaTemp, strButtonName);
					request.getSession().setAttribute("htmltext", sHtmlText);
					out.print("[{'suc':'1','msg':'订单生成成功，请到支付宝页面完成付款后继续操作。'}]");
				}else{
					out.print("[{'suc':'0','msg':'订单生成失败，请稍后重新操作。'}]");
				}
				
			}
		}else{
			msg = "系统中无对应的用户和手机号信息,请先完成用户手机验证。";
			out.print("[{'suc':'"+suc+"','msg':'"+msg+"'}]");
			return;
		}
		
//		response.sendRedirect("../jsp/alipay/alipayto.jsp");
//		try {
//			response.getWriter().write(sHtmlText);
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		//return new ModelAndView("alipay/alipayto.jsp");
	}
}
